<?php
// 开始输出缓冲区，防止意外输出干扰 header 操作
ob_start();

// 启动会话
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// 调试：记录会话数据和脚本启动日志
$log_file = 'debug.log'; // 调试日志文件路径
$log_data = "===== Debug Log Start =====\n";
$log_data .= "Session Status: " . session_status() . "\n";
$log_data .= "Session ID: " . session_id() . "\n";
$log_data .= "Session Data: " . print_r($_SESSION, true) . "\n";

// 检查管理员权限
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    $log_data .= "Redirect triggered: Unauthorized access.\n";
    file_put_contents($log_file, $log_data, FILE_APPEND); // 保存日志
    header('Location: http://localhost/Library_management_system/index.php');
    exit();
}
$log_data .= "Passed admin check.\n";

try {
    // 数据库连接
    $pdo = new PDO('mysql:host=localhost;dbname=library', 'root', '123456');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $log_data .= "Database connection successful.\n";

    // 查询违规记录
    $sql = "
        SELECT vr.violation_ID, vr.u_No, vr.violation_time, vrt.ViolationRecord_type
        FROM violationrecord AS vr
        INNER JOIN violationrecord_type AS vrt ON vr.ViolationRecord_ID = vrt.ViolationRecord_ID
        ORDER BY vr.violation_time DESC
    ";
    $stmt = $pdo->query($sql);
    $violations = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $log_data .= "Fetched violations: " . print_r($violations, true) . "\n";

} catch (PDOException $e) {
    $log_data .= "Database connection failed: " . $e->getMessage() . "\n";
    file_put_contents($log_file, $log_data, FILE_APPEND); // 保存日志
    die("数据库连接失败: " . htmlspecialchars($e->getMessage()));
}

// 记录执行到最后部分
$log_data .= "Script execution completed successfully.\n";
file_put_contents($log_file, $log_data, FILE_APPEND);

// 输出缓冲内容（如果需要）
ob_end_flush();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>查看所有用户违规记录</title>
</head>
<body>
    <h2>查看所有用户违规记录</h2>
    <?php if (!empty($violations)): ?>
        <ul>
            <?php foreach ($violations as $violation): ?>
                <li>
                    用户ID: <?php echo htmlspecialchars($violation['u_No']); ?>, 
                    违规类型: <?php echo htmlspecialchars($violation['ViolationRecord_type']); ?>, 
                    违规时间: <?php echo htmlspecialchars($violation['violation_time']); ?>
                </li>
            <?php endforeach; ?>
        </ul>
    <?php else: ?>
        <p>没有找到任何违规记录。</p>
    <?php endif; ?>
</body>
</html>
